//
//  M_UserVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/18.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_UserVC: BaseViewControllerWithHeader {
    let nameCard = UIView()
    let headImg = UIImageView()
    let nameLab = UILabel()
    let subLab = UILabel()
    let jfLab = UILabel()
    let jfSubLab = UILabel()
    
    let payCard = UIView()
    
    let welfareCard = UIView()
    var namelab = UILabel()
    var phonelab = UILabel()
    var pricelab = UILabel()
    var timelab = UILabel()
    var lqbtn = Button()
    
    var daizhifuTip = UILabel()
    var daifahuoTip = UILabel()
    var daishouhuoTip = UILabel()
    var yishouhuoTip = UILabel()
    var quanbuTip = UILabel()
    
    var gotoUrldicAry : [[String:Any?]]?
    let adCard = UIView()
    let adBtn = UIImageView()
    let adBtn1 = UIImageView()
    let toolCard = UIView()
    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        
        
//        let name1 = NSNotification.Name(rawValue:MALL_CHANGE)
//        NotificationCenter.default.addObserver(self, selector: #selector(notfifica(sender:)), name: name1, object: nil)
//        getCatchWelfare(pageIndex: 1, pageSize: 1, callback: { (item) in
//            let popup = PopupConfirmBox(info: "你有一个福利未领取，马上领取吗？", title: "福利")
//            popup.show(vc: UIViewController.topMostController() ?? self)
//            popup.onSureButtonClick = {
//                //确定执行
//                self.CatchWelfare(welfareConfigID: item.getString("welfareConfigID") ?? "", callback: {
//                    self.updateUI()
//                })
//            }
//        })
    }
    
    override func viewWillAppear(_ animated: Bool) {
        updateUI()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func getAllSysenterprise(callback: @escaping (Bool,[[String:Any?]]) -> Void) {
        API.formRequest(url: .YI_GetAllSysenterprise, params: nil, callback: { (result) in
            if result.success {
                if let dl = result.data?.getDictList("data") {
                    callback(result.success, dl)
                }
                else {
                    callback(result.success, [])
                }
            }
        })
    }

    func getSysadvertising(callback: @escaping (Bool,[[String: Any?]]) -> Void) {
        let dic1 = LocalStorage.getDic(forKey: DEFULT_MALL)
        var params :[String:Any] = ["type":2]

        getAllSysenterprise(callback: { (_,data) in
            if let dic = data.first(where: {$0.getString("mallID") == dic1?.getString("mallID")}) {
                params.updateValue(dic["id"] as Any, forKey: "enterpriseId")
                API.formRequest(url: .YI_GetSysadvertising, params: params, callback: { (result) in
                    if result.success {
                        if let dl = result.data?.getDictList("data") {
                            callback(result.success, dl)
                        }
                        else {
                            callback(result.success, [])
                        }
                    }
                    else {
                        callback(result.success, [])
                    }
                })
            }
        })
    }
    
    func getUserInfo() {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_GetUserInfo, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                LocalStorage.saveDic(dl, forKey: USER_INFO)
                self.nameLab.text = dl.getString("name")
                let dic = LocalStorage.getDic(forKey: DEFULT_MALL)
                self.subLab.text = dic?.getString("certifiedRemark")
                
                if var urlstring = dl.getString("headPic"),urlstring.count > 0 {
                    urlstring = (IMG_HOST_URL2+urlstring).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                    let url = URL(string: urlstring)
                    self.headImg.sd_setImage(with:url)
                }else{
                    self.headImg.image = UIImage.init(named: "touxiang_97")
                }
               }
                self.getMemCentAccountBalance()
            }else{
                let popup = PopupSureBox(title: result.errMsg ?? "登录失败，请重新登录", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    func getUserDifferentStateOrderQuantity(callback:@escaping ([String:Any?])->Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_GetUserDifferentStateOrderQuantity, params: params) { (result) in
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    callback(dl)
                }
            }else{
            }
        }
    }
    
    func getMemCentAccountBalance() {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_GetMemCentAccountBalance, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                self.jfLab.text = anyToString(dl["cents"] as Any?)
                self.jfSubLab.text = dl.getString("centUnitName")
               }
            }else{
            }
        }
    }
    
    func getCatchWelfare(pageIndex: Int, pageSize:Int,callback:@escaping ([String:Any?])->Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "pageIndex":pageIndex,
                                    "pageSize":pageSize,
                                    "sort":"107001",
                                    "dir":"106001"]
        API.request(url: .M_GetUserWelfareList, params: params) { (result) in
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    for item in dl.getDictList("items") ?? [] {
                        callback(item)
                        return
                    }
                }
            }
        }
    }
    
    func CatchWelfare(welfareConfigID: String,callback:@escaping ()->Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "welfareConfigID":welfareConfigID]
        API.request(url: .M_ReceiveWelfare, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
        }
    }
    
    func getWelfareList(pageIndex: Int, pageSize:Int,callback:@escaping ([String:Any?])->Void) {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "pageIndex":pageIndex,
                                    "pageSize":pageSize,
                                    "sort":"107001",
                                    "dir":"106001"]
        API.request(url: .M_GetUserWelfareFlowHistory, params: params) { (result) in
            if result.success {
                if let dl = result.data?.getDictionary("data") {
                    for item in dl.getDictList("items") ?? [] {
                        callback(item)
                        return
                    }
                }
            }
            self.welfareCard.snp_remakeConstraints{ (make) in
                make.top.equalTo(self.payCard.snp.bottom).offset(10)
                make.width.equalToSuperview()
                make.height.equalTo(0)
            }
            self.welfareCard.clipsToBounds = true
        }
    }
    
    func OpenWelfare(welfareRecordID: String,callback:@escaping ()->Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "welfareRecordID":welfareRecordID]
        API.request(url: .M_OpenWelfare, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                let popup = PopupBox(infoText: "领取成功")
                popup.show(vc: UIViewController.topMostController() ?? self)
                callback()
            }
            else {
                let popup = PopupBox(infoText:result.errMsg ?? "当前红包已打开")
                popup.show(vc: UIViewController.topMostController() ?? UIViewController())
            }
        }
    }
}

// MARK:- UI
extension M_UserVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
//        scrollView.addSubview(headView)
        headView.drawImage(named: "beijing_39") { (make) in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
        }
        headView.drawImage(named: "lepaidui_36") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton.snp.centerY).offset(2)
        }
        backButton.isHidden = true
        
        drawRightButton(imageName: "shezhi_35")
        .addTarget(self, action: #selector(_shezhiButtonClick(button:)), for: .touchUpInside)
        
//        drawRightButton(imageName: "xiaoxi_37")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_37")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        
        scrollView.drawView(view: nameCard) { (make) in
            make.top.equalToSuperview()
            make.height.equalTo(94)
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-20)
        }
        nameCard.backgroundColor = .white
        nameCard.layer.cornerRadius = 4
        
        scrollView.drawView(view:payCard) { (make) in
            make.top.equalTo(nameCard.snp.bottom).offset(10)
            make.width.equalToSuperview()
            make.height.equalTo(84.5)
        }
        payCard.backgroundColor = .white
        
        scrollView.drawView(view:welfareCard) { (make) in
            make.top.equalTo(payCard.snp.bottom).offset(10)
            make.width.equalToSuperview()
            make.height.equalTo(158)
        }
        welfareCard.backgroundColor = .white
        
        scrollView.drawView(view:adCard) { (make) in
            make.top.equalTo(welfareCard.snp.bottom).offset(10)
            make.width.equalToSuperview()
            make.height.equalTo(79.5)
        }
        adCard.backgroundColor = .clear
        
        scrollView.drawView(view:toolCard) { (make) in
            make.top.equalTo(adCard.snp.bottom).offset(10)
            make.width.equalToSuperview()
            make.height.equalTo(205.5)
        }
        toolCard.backgroundColor = .white
        
        setupNameCard(view: nameCard)
        setuppayCard(view: payCard)
        setupwelfareCard(view: welfareCard)
        setupadCard(view: adCard)
        setuptoolCard(view: toolCard)
        
        scrollView.bottomEqualTo(toolCard,offset:30)
    }
    
    func setupNameCard(view: UIView) {
        for v in view.subviews {
            v.removeFromSuperview()
        }
        
        let img = view.drawImage(named: "bg_icon") { (make) in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(65)
        }
        img.contentMode = .scaleToFill
        
        view.drawImage(imageView: headImg,named: "touxiang_97") { (make) in
            make.center.equalTo(img)
            make.width.height.equalTo(52)
        }
        headImg.clipsToBounds = true
        headImg.contentMode = .scaleAspectFit
        headImg.layer.cornerRadius = 52*0.5
        headImg.isUserInteractionEnabled = true
        headImg.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_headImgTap(tap:))))
        
        view.drawLabel(label: nameLab, text: "", fontSize: 18, fontWeight: .medium, textColor: .xFC4C02) { (make) in
            make.left.equalTo(view.snp.left).offset(84.5)
            make.centerY.equalTo(view.snp.top).offset(24.5+17*0.5)
        }
        
        view.drawLabel(label: subLab, text: "", fontSize: 12, fontWeight: .medium, textColor: .x666666) { (make) in
            make.left.equalTo(view.snp.left).offset(84.5)
            make.centerY.equalTo(view.snp.top).offset(58+11.5*0.5)
        }
        
        view.drawLabel(label: jfLab, text: "0", fontSize: 18, fontWeight: .bold, textColor: .x333333) { (make) in
            make.centerY.equalTo(view.snp.top).offset(34.5+14*0.5)
            make.centerX.equalTo(view.snp.right).offset(-15.5-57.5*0.5)
        }
        
        view.drawLabel(label: jfSubLab, text: "美晨积分", fontSize: 12, fontWeight: .medium, textColor: .x666666) { (make) in
            make.centerY.equalTo(view.snp.top).offset(54.5+11.5*0.5)
            make.centerX.equalTo(jfLab)
        }
    }
    
    func setuppayCard(view: UIView) {
        
        //统一绘制右上角的泡泡
        func drawTipLabel(label:UILabel, for image:UIView){
            view.drawLabel(label: label,text: label.text, fontSize: 8.0, fontWeight: .bold, textColor: .xFC4C02) { (make) in
                make.height.equalTo(10.5)
                make.centerX.equalTo(image.snp.right).offset(5.5-(14.4*0.5))
                make.top.equalTo(image)
            }
            label.layer.borderWidth = 1
            label.layer.borderColor = UIColor.xFC4C02.cgColor
            label.backgroundColor = .white
            label.layer.cornerRadius = 4.75
            label.clipsToBounds = true
            label.isHidden = true
        }
        
        var img = view.drawButton(imageNamed: "daizhifu_40") { (make) in
            make.left.equalToSuperview().offset(18.5)
            make.top.equalToSuperview().offset(20.5)
        }
        img.addTarget(self, action: #selector(_daizhifuButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "待支付", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        drawTipLabel(label: daizhifuTip, for: img)
        
//        view.drawLabel(label: daizhifuTip,text: daizhifuTip.text, fontSize: 9, textColor: .red) { (make) in
//            make.height.equalTo(14)
//            make.centerX.equalTo(img.snp.right).offset(-2)
//            make.top.equalTo(img)
//        }
//        // 设置边框
//        daizhifuTip.layer.borderWidth = 1
//        daizhifuTip.layer.borderColor = UIColor.red.cgColor
//        daizhifuTip.backgroundColor = .white
//        daizhifuTip.layer.cornerRadius = 8
//        daizhifuTip.clipsToBounds = true
//        daizhifuTip.isHidden = true
        
        img = view.drawButton(imageNamed: "daifahuo_41") { (make) in
            make.left.equalToSuperview().offset(91.5)
            make.top.equalToSuperview().offset(20.5)
        }
        img.addTarget(self, action: #selector(_daifahuoButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "待发货", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        drawTipLabel(label: daifahuoTip, for: img)
        
//        view.drawLabel(label: daifahuoTip,text: daifahuoTip.text, fontSize: 8.0, fontWeight: .bold, textColor: .xFC4C02) { (make) in
//            make.height.equalTo(10.5)
//            make.centerX.equalTo(img.snp.right).offset(5.5-(14.4*0.5))
//            make.top.equalTo(img)
//        }
//
//        daifahuoTip.layer.borderWidth = 1
//        daifahuoTip.layer.borderColor = UIColor.xFC4C02.cgColor
//        daifahuoTip.backgroundColor = .white
//        daifahuoTip.layer.cornerRadius = 4.75
//        daifahuoTip.clipsToBounds = true
//        daifahuoTip.isHidden = true
        
        img = view.drawButton(imageNamed: "daishouhuo_42") { (make) in
            make.left.equalToSuperview().offset(164.5)
            make.top.equalToSuperview().offset(20.5)
        }
        img.addTarget(self, action: #selector(_daishouhuoButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "待收货", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        drawTipLabel(label: daishouhuoTip, for: img)
        
//        view.drawLabel(label: daishouhuoTip,text: daishouhuoTip.text, fontSize: 9, textColor: .red) { (make) in
//            make.height.equalTo(16)
//            make.centerX.equalTo(img.snp.right).offset(-2)
//            make.top.equalTo(img)
//        }
//        daishouhuoTip.layer.borderWidth = 1
//        daishouhuoTip.layer.borderColor = UIColor.red.cgColor
//        daishouhuoTip.backgroundColor = .white
//        daishouhuoTip.layer.cornerRadius = 8
//        daishouhuoTip.clipsToBounds = true
//        daishouhuoTip.isHidden = true
        
        img = view.drawButton(imageNamed: "yishouhuo_43") { (make) in
            make.left.equalToSuperview().offset(237.5)
            make.top.equalToSuperview().offset(20.5)
        }
        img.addTarget(self, action: #selector(_yishouhuoButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "已收货", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        drawTipLabel(label: yishouhuoTip, for: img)
        
//        view.drawLabel(label: yishouhuoTip,text: yishouhuoTip.text, fontSize: 9, textColor: .red) { (make) in
//            make.height.equalTo(16)
//            make.centerX.equalTo(img.snp.right).offset(-2)
//            make.top.equalTo(img)
//        }
//        yishouhuoTip.layer.borderWidth = 1
//        yishouhuoTip.layer.borderColor = UIColor.red.cgColor
//        yishouhuoTip.backgroundColor = .white
//        yishouhuoTip.layer.cornerRadius = 8
//        yishouhuoTip.clipsToBounds = true
//        yishouhuoTip.isHidden = true
        
        //画横线
        let line = view.drawView { (make) in
            make.left.equalTo(img.snp.right).offset(25.5)
            make.top.equalToSuperview().offset(19.5)
            make.bottom.equalToSuperview().offset(-19.5)
            make.width.equalTo(0.5)
        }
        line.backgroundColor = .xF2F2F2
        
        img = view.drawButton(imageNamed: "quanbudingdan_44") { (make) in
            make.left.equalTo(line.snp.right).offset(25.5)
            make.top.equalToSuperview().offset(20.5)
        }
        img.addTarget(self, action: #selector(_quanbuButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "全部订单", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        drawTipLabel(label: quanbuTip, for: img)
        
//        view.drawLabel(label: quanbuTip,text: quanbuTip.text, fontSize: 9, textColor: .red) { (make) in
//            make.height.equalTo(14)
//            make.centerX.equalTo(img.snp.right).offset(-2)
//            make.top.equalTo(img)
//        }
//        quanbuTip.layer.borderWidth = 1
//        quanbuTip.layer.borderColor = UIColor.red.cgColor
//        quanbuTip.backgroundColor = .white
//        quanbuTip.layer.cornerRadius = 8
//        quanbuTip.clipsToBounds = true
//        quanbuTip.isHidden = true
    }
    
    func setupwelfareCard(view: UIView) {
        view.drawLabel(text: "福利领取", fontSize: 15, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(20)
        }
        let btn = view.drawButton(title: "查看我的福利 >", titleColor: .x999999, fontSize: 11) { (make) in
            make.top.equalToSuperview().offset(21.5)
            make.right.equalToSuperview().offset(-10)
        }
        btn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        btn.addTarget(self, action: #selector(_fuliButtonClick(button:)), for: .touchUpInside)
        
        //画横线
        let line = view.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(54.5)
            make.height.equalTo(0.5)
        }
        line.backgroundColor = .xF2F2F2
        
        let bgview = view.drawView() { (make) in
            make.top.equalTo(line.snp.bottom).offset(10)
            make.height.equalTo(73)
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().offset(-20)
        }
        bgview.backgroundColor = .xFE9A10
        bgview.layer.cornerRadius = 5

        phonelab = bgview.drawLabel(text: "1949494494", fontSize: 14, textColor: .white) { (make) in
            make.top.equalToSuperview().offset(26)
            make.left.equalToSuperview().offset(10)
        }
        phonelab.isHidden = true

        pricelab = bgview.drawLabel(text: "200.00", fontSize: 18, textColor: .white) { (make) in
            make.top.equalToSuperview().offset(17)
            make.right.equalToSuperview().offset(-10.5)
        }
        
        namelab = bgview.drawLabel(text: "账号激活积分自动到账体验", fontSize: 14, textColor: .white) { (make) in
            make.centerY.equalTo(pricelab)
            make.left.equalToSuperview().offset(10)
        }
        
        //画虚线
        bgview.drawView(view:DottdeView()) { (make) in
            make.left.equalToSuperview().offset(5)
            make.right.equalToSuperview().offset(-5)
            make.top.equalToSuperview().offset(46.5)
            make.height.equalTo(0.5)
        }
        
        timelab = bgview.drawLabel(text: "2019.08.29 - 2019.10.30", fontSize: 9, textColor: .white) { (make) in
            make.top.equalToSuperview().offset(57)
            make.left.equalToSuperview().offset(12.5)
        }
        lqbtn = bgview.drawButton(title: "领取", titleColor: .xFE9A10, fontSize: 11) { (make) in
            make.right.equalToSuperview().offset(-13.5)
            make.top.equalToSuperview().offset(52.5)
            make.width.equalTo(50)
            make.height.equalTo(15.5)
        }
        lqbtn.backgroundColor = .white
        lqbtn.layer.cornerRadius = 7.5
        lqbtn.addTarget(self, action: #selector(_fuliOpenButtonClick(button:)), for: .touchUpInside)
        lqbtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
    }
    
    func setupadCard(view: UIView) {
        view.drawView(view: adBtn, { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalTo(view.snp.centerX).offset(-5)
        })
        adBtn.tag = 0
        adBtn.isUserInteractionEnabled = true
        adBtn.layer.cornerRadius = 5
        adBtn.clipsToBounds = true
        adBtn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_adBtnTap(tap:))))
        
        view.drawView(view: adBtn1, { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
            make.left.equalTo(view.snp.centerX).offset(5)
        })
        adBtn1.tag = 1
        adBtn1.isUserInteractionEnabled = true
        adBtn1.layer.cornerRadius = 5
        adBtn1.clipsToBounds = true
        adBtn1.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_adBtn1Tap(tap:))))
    }
    
    func setuptoolCard(view: UIView) {
        view.drawLabel(text: "工具与服务", fontSize: 15, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(20)
        }
        
        //画横线
        let line = view.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(46.5)
            make.height.equalTo(0.5)
        }
        line.backgroundColor = .xF2F2F2
        
       var img = view.drawButton(imageNamed: "shoucan_45") { (make) in
            make.left.equalToSuperview().offset(50)
            make.top.equalTo(line.snp.bottom).offset(20)
        }
        img.addTarget(self, action: #selector(_shoucanButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "收藏", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        
        img = view.drawButton(imageNamed: "jifenmingxi_46") { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(line.snp.bottom).offset(20)
        }
        img.addTarget(self, action: #selector(_jifenmingxiButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "积分明细", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        
        img = view.drawButton(imageNamed: "guanyuwomen_47") { (make) in
            make.right.equalToSuperview().offset(-50)
            make.top.equalTo(line.snp.bottom).offset(20)
        }
        img.addTarget(self, action: #selector(_guanyuwomenButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "关于我们", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        
         img = view.drawButton(imageNamed: "bangzhu_48") { (make) in
             make.left.equalToSuperview().offset(50)
            make.top.equalTo(line.snp.bottom).offset(88.5)
         }
         img.addTarget(self, action: #selector(_bangzhuButtonClick(button:)), for: .touchUpInside)
         img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
         view.drawLabel(text: "帮助", fontSize: 11, textColor: .x666666) { (make) in
             make.centerX.equalTo(img.snp.centerX)
             make.top.equalTo(img.snp.bottom).offset(6.5)
         }
        
        img = view.drawButton(imageNamed: "yijian") { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(line.snp.bottom).offset(88.5)
        }
        img.addTarget(self, action: #selector(_yijianButtonClick(button:)), for: .touchUpInside)
        img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
        view.drawLabel(text: "意见反馈", fontSize: 11, textColor: .x666666) { (make) in
            make.centerX.equalTo(img.snp.centerX)
            make.top.equalTo(img.snp.bottom).offset(6.5)
        }
        
        if LocalStorage.getBool(forKey: ISINREVIEW) ?? false {
            img = view.drawButton(imageNamed: "daizhifu_40") { (make) in
                make.right.equalToSuperview().offset(-50)
                make.top.equalTo(line.snp.bottom).offset(88.5)
            }
            img.addTarget(self, action: #selector(_yufukuanButtonClick(button:)), for: .touchUpInside)
            img.hitEdgInsets = .init(top: -10, left: -10, bottom: -40, right: -10)
            view.drawLabel(text: "预付款", fontSize: 11, textColor: .x666666) { (make) in
                make.centerX.equalTo(img.snp.centerX)
                make.top.equalTo(img.snp.bottom).offset(6.5)
            }
        }
    }
    
    func updateUI() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.getUserInfo()
            self.getMemCentAccountBalance()
        }
        
        getWelfareList(pageIndex: 1, pageSize: 1, callback: { (data) in
            self.namelab.text = data.getString("welFareName")
            let btime = data.getString("actionBTime")?.prefix(10) ?? "现在"
            let etime = data.getString("actionETime")?.prefix(10) ?? "至今"
            self.timelab.text = btime.replacingOccurrences(of: "-", with: ".") + "-" + etime.replacingOccurrences(of: "-", with: ".")
//            let cents = String(format:"%.2f",data.getDouble("cents") ?? 0)
            self.pricelab.text = data.getString("cents")
            self.phonelab.text = data.getString("welfareRecordID") ?? ""
            if data.getString("welfareStatusCode") ==  "120001" {
                self.lqbtn.setTitle("已领取", for: .normal)
                self.lqbtn.alpha = 0.6
                self.lqbtn.tag = 0
            }
            else if data.getString("welfareStatusCode") ==  "120002" {
                self.lqbtn.setTitle("领取", for: .normal)
                self.lqbtn.alpha = 1
                self.lqbtn.tag = 1
            }
            self.welfareCard.snp_remakeConstraints{ (make) in
                make.top.equalTo(self.payCard.snp.bottom).offset(10)
                make.width.equalToSuperview()
                make.height.equalTo(158)
            }
            self.welfareCard.clipsToBounds = true
        })
        
        getUserDifferentStateOrderQuantity(callback: { (data) in
            if ((anyToInt(data["waittingPayOrderQuantity"] as Any?)) ?? 0 > 0) {
                let showNumber = anyToInt(data["waittingPayOrderQuantity"] ?? "")!
                self.daizhifuTip.setBubbleNumber(showNumber)
                self.daizhifuTip.isHidden = false
            }
            else {
                self.daizhifuTip.isHidden = true
            }
            
            if ((anyToInt(data["awaitDeliverOrderQuantity"] as Any?)) ?? 0 > 0) {
                let showNumber = anyToInt(data["awaitDeliverOrderQuantity"] ?? "")!
                self.daifahuoTip.setBubbleNumber(showNumber)
                self.daifahuoTip.isHidden = false
            }
            else {
                self.daifahuoTip.isHidden = true
            }
            
            if ((anyToInt(data["deliveredOrderQuantity"] as Any?)) ?? 0 > 0) {
                let showNumber = anyToInt(data["deliveredOrderQuantity"] ?? "")!
                self.daishouhuoTip.setBubbleNumber(showNumber)
                self.daishouhuoTip.isHidden = false
            }
            else {
                self.daishouhuoTip.isHidden = true
            }
            
            if ((anyToInt(data["receivedOrderQuantity"] as Any?)) ?? 0 > 0) {
                let showNumber = anyToInt(data["receivedOrderQuantity"] ?? "")!
                self.yishouhuoTip.setBubbleNumber(showNumber)
                self.yishouhuoTip.isHidden = true
            }
            else {
                self.yishouhuoTip.isHidden = true
            }
            
            var quanbu = (anyToInt(data["waittingPayOrderQuantity"] as Any?) ?? 0) +
            (anyToInt(data["awaitDeliverOrderQuantity"] as Any?) ?? 0) +
            (anyToInt(data["deliveredOrderQuantity"] as Any?) ?? 0)
            quanbu += (anyToInt(data["receivedOrderQuantity"] as Any?) ?? 0) +
            (anyToInt(data["cancelOrderQuantity"] as Any?) ?? 0)
            if (quanbu > 0) {
                self.quanbuTip.setBubbleNumber(quanbu)
                //永远不显示吗？
                self.quanbuTip.isHidden = true
            }
            else {
                self.quanbuTip.isHidden = true
            }
        })

        getSysadvertising(callback: { (sec,data) in
            if sec,data.count > 0 {
                let imgurlAry = data[0].getString("imgs")?.toJSONDictList()
                var imgAry = [String]()
                for i in 0...(imgurlAry?.count ?? 0)-1 {
                    if let dic = imgurlAry?[i] {
                        if let imgUrl = anyToString(dic["img"] as Any?),imgUrl.count > 0{
                            imgAry.append(imgUrl)
                        }
                    }
                }
                self.adBtn.sd_setImage(with: URL.init(string: imgAry[0]))
                self.adBtn1.sd_setImage(with: URL.init(string: imgAry[1]))
                self.adCard.snp_remakeConstraints { (make) in
                    make.top.equalTo(self.welfareCard.snp.bottom).offset(10)
                    make.width.equalToSuperview()
                    make.height.equalTo(79.5)
                }
                self.adCard.backgroundColor = .clear
                
                self.gotoUrldicAry = data[0].getString("url")?.toJSONDictList()?.filter({ (dic) -> Bool in
                    if let url = anyToString(dic["url"] ?? ""),url.count > 0 {
                        return true
                    }
                    return false
                })
            }
            else {
                self.adCard.snp_remakeConstraints { (make) in
                    make.top.equalTo(self.welfareCard.snp.bottom).offset(10)
                    make.width.equalToSuperview()
                    make.height.equalTo(0)
                }
                self.adCard.backgroundColor = .clear
            }
        })
    }
}

// MARK:- 事件
extension M_UserVC {
    
    @objc func notfifica(sender:NSNotification) {
        updateUI()
    }
    
    @objc func _adBtnTap(tap:UITapGestureRecognizer) {
        if gotoUrldicAry?.count ?? 0 > 0,let dic = gotoUrldicAry?[0] {
            switch anyToInt(dic["special"] ?? -1) {
            case 0:
                if var url = anyToString(dic["url"] ?? "") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    url = SPLICE_URL + url
                    vc.dataDic = dic
                    vc.loadUrl(url)
                }
            case 1:
                if let url = anyToString(dic["url"] ?? "") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    vc.dataDic = dic
                    vc.loadUrl(url)
                }
            default:
                break
            }
        }
    }
    
    @objc func _adBtn1Tap(tap:UITapGestureRecognizer) {
        if gotoUrldicAry?.count ?? 0 > 1,let dic = gotoUrldicAry?[1] {
            switch anyToInt(dic["special"] ?? -1) {
            case 0:
                if var url = anyToString(dic["url"] ?? "") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    url = SPLICE_URL + url
                    vc.dataDic = dic
                    vc.loadUrl(url)
                }
            case 1:
                if let url = anyToString(dic["url"] ?? "") {
                    let vc = M_ArticleVC()
                    pushViewController(vc)
                    vc.dataDic = dic
                    vc.loadUrl(url)
                }
            default:
                break
            }
        }
    }
    
    @objc func _headImgTap(tap:UITapGestureRecognizer) {
        let vc = M_SettingVC()
        pushViewController(vc)
    }
    
    @objc func _quanbuButtonClick(button: Button) {
        let vc = M_OrderListVC(zoneCode:ZoneCodeModel(fromDictionary: ["name" : "全部订单",
                                                                     "sort" : 2,
                                                                     "code" : "100012"]))
        pushViewController(vc)
    }
    
    @objc func _daizhifuButtonClick(button: Button) {
        let vc = M_OrderListVC(zoneCode:ZoneCodeModel(fromDictionary: ["name" : "待支付",
                                                                     "sort" : 2,
                                                                     "code" : "100013"]))
        pushViewController(vc)
    }
    
    @objc func _daishouhuoButtonClick(button: Button) {
        let vc = M_OrderListVC(zoneCode:ZoneCodeModel(fromDictionary: ["name" : "待收货",
                                                                     "sort" : 2,
                                                                     "code" : "100015"]))
        pushViewController(vc)
    }
    
    @objc func _daifahuoButtonClick(button: Button) {
        let vc = M_OrderListVC(zoneCode:ZoneCodeModel(fromDictionary: ["name" : "待发货",
                                                                     "sort" : 2,
                                                                     "code" : "100014"]))
        pushViewController(vc)
    }
    
    @objc func _yishouhuoButtonClick(button: Button) {
        let vc = M_OrderListVC(zoneCode:ZoneCodeModel(fromDictionary: ["name" : "已收货",
                                                                     "sort" : 2,
                                                                     "code" : "100016"]))
        pushViewController(vc)
    }
    
    @objc func _qeuxiaoButtonClick(button: Button) {
        let vc = M_OrderListVC(zoneCode:ZoneCodeModel(fromDictionary: ["name" : "订单取消",
                                                                     "sort" : 2,
                                                                     "code" : "100017"]))
        pushViewController(vc)
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func _shezhiButtonClick(button: Button) {
        let vc = M_SettingVC()
        pushViewController(vc)
    }
    
    
    @objc func _shoucanButtonClick(button: Button) {
        let vc = M_FavListVC()
        pushViewController(vc)
    }
    
    @objc func _jifenmingxiButtonClick(button: Button) {
        let vc = M_JifenVC()
        pushViewController(vc)
    }
    
    @objc func _guanyuwomenButtonClick(button: Button) {
        let vc = M_AboutVC()
        pushViewController(vc)
    }
    
    @objc func _fuliButtonClick(button: Button) {
        let vc = M_FuliVC()
        pushViewController(vc)
    }
    @objc func _fuliOpenButtonClick(button: Button) {
        OpenWelfare(welfareRecordID: phonelab.text ?? "", callback: {
            self.getWelfareList(pageIndex: 1, pageSize: 1, callback: { (data) in
                self.namelab.text = data.getString("welFareName")
                let btime = data.getString("actionBTime") ?? "现在"
                let etime = data.getString("actionETime") ?? "至今"
                self.timelab.text = btime + "-" + etime
//                let cents = data.getInt("cents") ?? 0
//                self.pricelab.text = String(format:"%.2f",data.getDouble("cents") ?? 0)
                self.phonelab.text = data.getString("welfareRecordID") ?? ""
                if data.getString("welfareStatusCode") ==  "120001" {
                    self.lqbtn.setTitle("已领取", for: .normal)
                    self.lqbtn.alpha = 0.6
                }
                else if data.getString("welfareStatusCode") ==  "120002" {
                    self.lqbtn.setTitle("领取", for: .normal)
                    self.lqbtn.alpha = 1
                    
                }
            })
        })
    }
    
    @objc func _bangzhuButtonClick(button: Button) {
        let vc = M_HelperVC()
        pushViewController(vc)
    }
    
    @objc func _yijianButtonClick(button: Button) {
        let vc = M_OpinionVC()
        pushViewController(vc)
    }
    @objc func _yufukuanButtonClick(button: Button) {
        let vc = AppPayVC()
        pushViewController(vc)
    }
}

class DottdeView : UIView {
//    var dottcolor : UIColor
//    init(color : UIColor) {
//        self.dottcolor = color
//        super.init(frame:.zero)
//    }
    
//    required init?(coder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        for layer in self.layer.sublayers ?? [] {
            layer.removeFromSuperlayer()
        }
        let curRect = self.bounds
        if curRect.width > curRect.height {
            drawDottedLine(start: CGPoint(x: 0, y: curRect.height/2), end: CGPoint(x: curRect.width, y: curRect.height/2), color: .white, thick: curRect.height, dashLength: 3, gapLength: 1)
        }
        else {
            drawDottedLine(start: CGPoint(x: curRect.width/2, y: 0), end: CGPoint(x: curRect.width/2, y: curRect.height), color: .white, thick: curRect.width, dashLength: 3, gapLength: 1)
        }
    }
    
    func drawDottedLine(start p0: CGPoint, end p1: CGPoint, color:UIColor,thick:CGFloat, dashLength:Int,gapLength:Int){
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = color.cgColor
        shapeLayer.lineWidth = thick
        shapeLayer.lineDashPattern = [NSNumber(value: dashLength), NSNumber(value: gapLength)]
        let path = CGMutablePath()
        path.addLines(between: [p0, p1])
        shapeLayer.path = path
        self.layer.addSublayer(shapeLayer)
    }
}
